package com.init.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.init.common.ErrorCode;
import com.init.exception.BusinessException;
import com.init.mapper.AdminMapper;
import com.init.mapper.GradersMapper;
import com.init.model.dto.LoginUser;
import com.init.model.entity.Admin;
import com.init.model.entity.Graders;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;


/**
 * SpringSecurity登录认证
 * @author Atanycosts
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private AdminMapper adminMapper;


    @Resource
    private GradersMapper gradersMapper;

    /**
     * 登录
     * @param userAccount
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String userAccount) throws UsernameNotFoundException {
        // 管理员表查
        LambdaQueryWrapper<Admin> wrapperHospital = new LambdaQueryWrapper<>();
        wrapperHospital.eq(Admin::getAdminAccount, userAccount);

        Admin admin = adminMapper.selectOne(wrapperHospital);
        if (Objects.nonNull(admin)) {

            List<String> list = new ArrayList<>(Arrays.asList(admin.getAdminRole()));
            // 封装成UserDetails对象返回
            return new LoginUser(admin, list);
        }

        // 用户表查
        LambdaQueryWrapper<Graders> wrapperUser = new LambdaQueryWrapper<>();
        wrapperUser.eq(Graders::getUserAccount, userAccount);

        Graders graders = gradersMapper.selectOne(wrapperUser);
        // 如果查询不到数据就通过抛出异常来给出提示
        if (Objects.nonNull(graders)) {

            List<String> list = new ArrayList<>(Arrays.asList(graders.getUserRole()));
            // 封装成UserDetails对象返回
            return new LoginUser(graders, list);
        }

        throw new BusinessException(ErrorCode.OPERATION_ERROR, "用户不存在~~");
    }
}